/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-04-04",
  "license": "MIT",
*/


/**
 * 创建随机数
 * @param length 随机数长度
 */
 exports.randomNumber = function (length = 32) {
    let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    str += '0123456789'
    let _str = ''
    for (let i = 0; i < length; i++) {
        var rand = Math.floor(Math.random() * str.length)
        _str += str[rand];
    }
    return _str
}

/*
* 删除对象数组的某个key
*@param {Array} target 目标数组
*@param {Array || String} keys 删除的key
*/
exports.deleteJsonKey = function(target, keys) {
	if (target.length == 0) {
	  return target
	}
	let result = []
	if (Array.isArray(keys)) {
	  let mixed = Object.keys(...target).filter(x => !new Set(keys).has(x))
	  result = JSON.parse(JSON.stringify(target, mixed))
	} else {
	  result = JSON.parse(JSON.stringify(target, (k, v) => {
		if (k !== keys) {
		  return v
		}
	  }))
	}
	return result
}

/*
* 删除对象的某个key
*@param {Object} 目标对象
*@param {String} key 删除的key
*/
exports.deleteKey = (prop, { [prop]: _, ...rest }) => rest

/*
* 日期格式化
*@param {Object | string} 时间/时间戳 
*@param {String} 格式
*/

exports.parseTime = function(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
exports.handleMenuTree = function(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}


/**
 * 首字母大写
 * @param {string} 字母
 */ 
exports.titleCase = function(str) {  
    return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());  
}

/*
*name: 返回单表总数量
*@param {function} 请求数据库方法
*@param {string} tableName 表名
*/
exports.getTableTotal = function(connection, sql) {
	return new Promise((resolve, reject) => {
		connection(sql, (error, result, fileds) =>{
			console.log(error);
			if(error) {
				reject(error)
			}else{
				let total = result[0]['total']
				resolve(total)
			}
		})
	})
}

/*
*name: 更新数据返回sql值
*@param {object} 从前端传过来的更新数据
*/
exports.updateDataSql = function(obj) {
	// delete obj.create_time;
	// delete obj.create_time;
	let keysArray = Object.keys(obj);
	let setArray = [];
	
	keysArray.forEach(item => {
		let sqlVal = ` ${item} = '${obj[item]}'`
		setArray.push(sqlVal)
	})

	let keysString = setArray.join(',')
	return keysString;
}

/*
*name: 记录操作日志
*@param {function} 链接数据库方法
*@param {string} 操作事项
*@param {object} 用户token数据
*/
exports.recordOperaLog = (connection, msg, userTokenData) => {
		const id = this.randomNumber();
		const data = {
			id,
			operator: userTokenData.name,
			operaEvent: msg,
			operaTime: new Date(),
			isDelete: '1'
		}
		const sql = 'INSERT INTO operaInfo SET?';
		connection(sql, data, (error, result, fileds) => {
		    if(error) {
		        console.log(error)
		    } else {
		        // 返回
		        console.log('记录操作事项成功')
		    }
		})
	}